<template>
  <div class="app-container">
    <el-form  class="query-wrapper" :model="queryParams" inline>
      <el-form-item  prop="supplierCode">
        <el-input v-model="queryParams.supplierCode" style="width: 180px" placeholder="Supplier Code" clearable />
      </el-form-item>
      <el-form-item  prop="fullName">
        <el-input v-model="queryParams.fullName" style="width: 180px" placeholder="Full Name" clearable /> 
      </el-form-item>
      <el-form-item>
       
        <el-button type="primary" icon="search" v-hasPermi="['supplier:get']"  @click="search">{{
          $t("ship.button.search")
        }}</el-button>
         <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
         &nbsp;&nbsp;
        <el-button type="primary" plain icon="Plus" @click="addClickEvent"  v-hasPermi="['supplier:add']">
          {{ $t("ship.button.plus") }}
        </el-button> 
      </el-form-item>
    </el-form>
  </div>

  <el-table ref="tableRef"  stripe :border="true" :data="listData" style="width: 100%" @sort-change="handleSortChange" show-overflow-tooltip>
    <el-table-column prop="supplierCode" label="Supplier Code" width="120" />
    <el-table-column prop="fullName" label="Full Name" width="300" />
    <el-table-column prop="supplierType" label="Supplier Type"  width="150"/>
    <el-table-column prop="phone" label="Phone"  width="150"/>
    <el-table-column prop="email" label="Email"  width="160"/>   
    <!-- <el-table-column prop="fax" label="Fax" />  -->
 
    <el-table-column prop="photo" label="Photo"   v-hasPermi="['supplier:upload']" width="180"> 
      <template #default="scope" class="image_content">	   
        <PreViewImageUpload :record="scope.row" :photos="Array.isArray(scope.row.photos)?scope.row.photos:scope.row.photos?[scope.row.photos]:[]"
          :url="uploadUrl"
          :id="scope.row.supplierId"
          @onSuccess="submitUploadForm" :isDelSub="true" @onDelete="deleteFile"  />
      </template>
    </el-table-column>
    <el-table-column prop="status" label="Status" width="150" v-hasPermi="['supplier:audit']">
      <template #default="scope"> 
        <el-select
              v-model="scope.row.status"
              class="ipt"
              clearable 
              :disabled="scope.row.status == 1 || scope.row.satus == 2"
              @change="handleStatus(scope.row)"
            >
              <el-option :key="index" :label="item" :value="index" v-for="(item,index) in  statuss"  
               />
            </el-select>
      </template>  
    </el-table-column> 
    <el-table-column prop="createBy" label="Created By" width="100" />
    <el-table-column label="Operation" width="200" v-hasPermi="['supplier:edit']" fixed="right">
      <template #default="scope">
        <span class="btn-primary" @click="editClickEvent(scope.row)">{{
          $t("ship.button.edit")
        }}</span>&nbsp;&nbsp;
        <span class="btn-primary" :disabled="scope.row.status == 1" @click="removeClickEvent(scope.row.supplierId)">{{
          $t("ship.button.remove")
        }}</span>&nbsp;&nbsp;
        <span class="btn-primary"  @click="bankInfoClickEvent(scope.row.supplierId)">{{
          $t("ship.button.bankInfo")
        }}</span>
      </template>
    </el-table-column>
  </el-table>

  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog :width="500" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="24">
          <el-form-item label="Supplier Code" label-width="120px" prop="supplierCode" required>
            <el-input v-model="formParam.supplierCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Full Name" label-width="120px" prop="fullName" required>
            <el-input v-model="formParam.fullName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Contact Name" label-width="120px" prop="contactName" required>
            <el-input v-model="formParam.contactName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Mobile" label-width="120px" prop="mobile" required>
            <el-input v-model="formParam.mobile"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Email" label-width="120px" prop="email" required>
            <el-input v-model="formParam.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button>
        <el-button @click="resetForm" type="warning">{{
          $t("ship.button.reset")
        }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
  <SupplierModal ref="formModal" @refreshTable="refreshTable"/>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
import service from "@/utils/request"; 
import { useTableDrag } from '@/hooks/useHooks'
import { ElNotification, ElMessageBox } from "element-plus";
import SupplierModal from './supplierModal'
import PreViewImageUpload from '@/components/ImageUpload/PreViewImageUpload.vue'
const { tableRef } = useTableDrag();
import { convertUrl } from "@/utils/tencentCos";
const uploadUrl = '/shipping/supplier/upload'   //上传接口
const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
  supplierId: null,
  fullName: null,
  supplierCode: null,
  contactName: null,
  mobile: null,
  email: null,
};
const formParam = reactive(Object.assign({}, initForm));

const total = ref(0);
const statuss = ['UnApprove', "Approve", "Reject"]
const mailValid = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("email can't be blank"));
  } else if (!/^(?:\w+\.?)*\w+@(?:\w+\.)*\w+$/.test(value)) {
    callback(new Error('The email format is illegal!'));
  } else {
    callback();
  }
}
const rules = ref({
  email: [{ required: true, trigger: "blur", validator: mailValid }]
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  supplierCode: null,
  fullName: null,
  orderByColumn: undefined,
  isAsc: undefined,
});

let urlmap = {};
const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/supplier/getTable", { params: queryParams });
  listData.value = result.data;

  urlmap={}
    Object.keys(listData.value).forEach(key => {
     let photos=listData.value[key].photos
     if(photos){
          Object.keys(photos).forEach(key2 => {
              let tt=photos[key2]
              photos[key2]= convertUrl( photos[key2])
              urlmap[photos[key2]]= tt
          })
     }
    })

  total.value = result.total;
};
const resetQuery = (data) => {
  Object.assign(queryParams, data)
  refreshTable()
}
const dialogFormVisible = ref(false);

const editClickEvent = (row: any) => {
  row.title = "Update Supplier"
  formModal.value.show(row);
};

let isAdd = false;
const formModal = ref();
const addClickEvent = () => { 
  formModal.value.show();
};

const handleStatus=(row:any)=>{
  if(row.status != null && row.status != 0){
    ElMessageBox.confirm("Confirm to update the Supplier Status？", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => { 
        await service.put(`shipping/supplier`, row);
        ElNotification.success({
          title: "Prompt information",
          message: "Update booking status success!",
          position: "bottom-right"
        });
        
      });
  }
}


const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
 
    await service[isAdd ? "post" : "put"]("shipping/supplier", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    refreshTable();
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
};


const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const removeClickEvent = (id) => {
  ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.delete(`shipping/supplier/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};

const bankInfoClickEvent = (id) => {
  router.push({ path: "/basicData/bankInfo", query: { id: id, type: 2 } })
}

// 上传成功更新数据
const submitUploadForm = async (data) => { 
  // @ts-ignore
  const params = {
    supplierId: data.id,
    photos: data.photos
  };
 
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  refreshTable();
};

const deleteFile = async (data) => { 
  let url= urlmap[data.url]
  const params = {
    id: data.id,
    url: url,
  };
  await service["post"]("/shipping/supplier/deleteFile", params);

  refreshTable();
};

 
onMounted(async () => {
  refreshTable();
});
</script>
<style lang="scss" scoped>
.el-table__expand-column .cell {
  display: none;
}
::v-deep.el-table td.el-table__cell div{
    text-align: center;
  }
.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.c-expand i {
  font-size: 16px;
}

.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}
</style>
